import './Peripheral.scss'
import { useState, useEffect } from 'react'
import { useRequest, useEventEmitter } from 'ahooks'
import { Tree, Dropdown, Button, notification } from 'antd'
import { DownOutlined, UpOutlined, AudioOutlined, NodeIndexOutlined } from '@ant-design/icons'

import { project } from '../../../../Common/Data'

import { ZLBox } from '../Command/ZL'
import { CMTBox } from '../Command/CMT'
import { FrontModalBox } from '../Modal'
import { MapA01 } from '../Template/Map'
import { deviceList } from '../Command/KING'
import { Http } from '../../../../Common/Api'
import { PeripheralMapA01 } from './PeripheralMap'
import { CommonSmallTitle } from '../Common/SmallTitle'
import { findValue } from '../../../../Common/Configure/Common'
import { InitLionKing, DestructionKing } from '../Command/KING'
import { disconnectedCallback, deviceAlarmDone } from '../Command/KING'
import { SDK_STATE, DEVICE_STATE, DEVICE_ALARM_STATE } from '../Command/KING'
import { microphoneMutilBoradcastStop, audioSpeakStop, videoMonitorStop } from '../Command/KING'
import { microphoneMutilBoradcastStart, audioSpeakStart, videoMonitorStart } from '../Command/KING'

const { SOS } = window
const { hostname } = window.location

const { client_id, imageUrl } = project[hostname]

const MapList = { MapA01, PeripheralMapA01 }

const menuTypeList = {
    A01: '安全帽',
    B01: 'IP广播',
    C01: '现场监控',
    D01: 'SOS预警',
}

const StatusList = {
    0: '离线',
    1: '在线',
    2: '离线',
    11: '呼叫中...',
    12: '通话中...',
}
const ApiStatus = ['jszx.ljkjkf.com']

const A01 = ({ CMT_ADMIN, ZL_ADMIN, sceneId, org }) => {
    const CMTEvent = useEventEmitter()
    const ZLEvent = useEventEmitter()
    const [UserList, setUserList] = useState()
    const [UserStatus, setUserStatus] = useState({})
    const [Select, setSelect] = useState()
    const [OptionsCall, setOptionsCall] = useState()
    const [OrgDetails, setOrgDetails] = useState()

    const { runAsync: getJSZX } = useRequest(Http, {
        manual: true,
        onSuccess: res => setUserList(res),
    })

    const { runAsync: getOther } = useRequest(Http, {
        manual: true,
        onSuccess: res => setUserList(res.helmet),
    })

    const { runAsync: getOrg } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            if (res.customData) setOrgDetails(JSON.parse(res.customData))
            else setOrgDetails(null)
        },
    })

    useEffect(() => {
        ApiStatus.includes(hostname)
            ? getJSZX({ url: 'getSecurityStatHelmetTree' })
            : getOther({ url: 'getTalkHelmet', data: { OrganizationUuid: org } })
    }, [getJSZX, getOther, org])

    const select = e => {
        if (e.length !== 0) setSelect(e)
    }
    const call = () => {
        const { helmetType, deviceSerial } = findValue(UserList, 'uuid', Select[0])
        if (helmetType === 1) CMTEvent.emit(deviceSerial)
        if (helmetType === 3) ZLEvent.emit(deviceSerial)
    }

    const trajectory = e => {
        setOptionsCall({
            type: 'CommandTrajectory',
            data: { title: e.personName + '历史轨迹', data: { ren: e, sceneId: sceneId } },
        })
    }

    const UserEvent = useEventEmitter()
    UserEvent.useSubscription(val => {
        setUserStatus(e => ({ ...e, ...val }))
    })

    const items = e => [
        {
            key: '1',
            label: <div onClick={call}>开始呼叫</div>,
            icon: <AudioOutlined />,
        },
        {
            key: '2',
            label: <div onClick={() => trajectory(e)}>历史轨迹</div>,
            icon: <NodeIndexOutlined />,
        },
    ]

    const onClick = e => {
        if (client_id === 'nongken') getOrg({ url: 'getOrganizationID', path: [e.organizationUuid] })
    }

    return (
        <div className="PeripheralA01">
            <Tree
                fieldNames={{ title: 'personName', key: 'uuid' }}
                selectedKeys={Select}
                onSelect={select}
                treeData={UserList}
                titleRender={e => {
                    const { deviceSerial, personName, parentUuid } = e
                    return (
                        <>
                            {parentUuid === '00000000-0000-0000-0000-000000000000' ? (
                                <div>{personName}</div>
                            ) : (
                                <Dropdown menu={{ items: items(e) }} trigger={['click']}>
                                    <div className="personName" onClick={() => onClick(e)}>
                                        <div>
                                            {deviceSerial} - {personName}
                                        </div>
                                        <div>{StatusList[UserStatus[deviceSerial]] || '初始化...'}</div>
                                    </div>
                                </Dropdown>
                            )}
                        </>
                    )
                }}
            />
            {CMT_ADMIN && <CMTBox CMT_ADMIN={CMT_ADMIN} UserEvent={UserEvent} CMTEvent={CMTEvent} />}
            {ZL_ADMIN && <ZLBox ZL_ADMIN={ZL_ADMIN} UserEvent={UserEvent} ZLEvent={ZLEvent} />}
            <FrontModalBox OptionsCall={OptionsCall} />
            {OrgDetails && (
                <div className="OrgBox">
                    <div className="image imageA1">
                        <img src={imageUrl + 'MapA01.png'} alt="" />
                    </div>
                    <div className="image imageA2">
                        <img src={imageUrl + 'MapA01.png'} alt="" />
                    </div>
                    <div className="image imageA3">
                        <img src={imageUrl + 'MapA01.png'} alt="" />
                    </div>
                    <div className="image imageA4">
                        <img src={imageUrl + 'MapA01.png'} alt="" />
                    </div>
                    <img className="imageBack" src={imageUrl + 'MapA02.png'} alt="" />

                    <div className="Title">
                        <div>项目信息</div>
                        <div />
                    </div>
                    <div className="ClassBox ClassA">
                        <div className="ClassA01">
                            <div>{OrgDetails[0].thr} : </div>
                            <div>{OrgDetails[0].fou}</div>
                        </div>
                        <div className="ClassA02">
                            <div>{OrgDetails[1].thr} : </div>
                            <div>{OrgDetails[1].fou}</div>
                        </div>
                    </div>
                    <div className="ClassBox ClassB">
                        <div>
                            <div>
                                <div>{OrgDetails[2].thr} : </div>
                                <div>{OrgDetails[2].fou}</div>
                            </div>
                            <div>
                                <div>{OrgDetails[2].fiv} : </div>
                                <div>{OrgDetails[2].six}</div>
                            </div>
                        </div>
                        <div>
                            <div>
                                <div>{OrgDetails[3].thr} : </div>
                                <div>{OrgDetails[3].fou}</div>
                            </div>
                            <div>
                                <div>{OrgDetails[3].fiv} : </div>
                                <div>{OrgDetails[3].six}</div>
                            </div>
                        </div>
                        <div>
                            <div>
                                <div>{OrgDetails[4].thr} : </div>
                                <div>{OrgDetails[4].fou}</div>
                            </div>
                            <div>
                                <div>{OrgDetails[4].fiv} : </div>
                                <div>{OrgDetails[4].six}</div>
                            </div>
                        </div>
                    </div>
                    <div className="ClassBox ClassC">
                        <div className="ClassC01">
                            <div>{OrgDetails[5].thr} : </div>
                            <div>{OrgDetails[5].fou}</div>
                        </div>
                        <div className="ClassC01">
                            <div>{OrgDetails[6].thr} : </div>
                            <div>{OrgDetails[6].fou}</div>
                        </div>
                    </div>
                    <div className="ClassBox ClassD">
                        <div className="ClassD01">
                            <div>{OrgDetails[7].thr} : </div>
                            <div>{OrgDetails[7].fou}</div>
                        </div>
                        <div className="ClassD01">
                            <div>{OrgDetails[8].thr} : </div>
                            <div>
                                {OrgDetails[8].fou} {OrgDetails[8].fiv}{' '}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    )
}

const B01 = ({ KING_ADMIN, org }) => {
    const [api, contextHolder] = notification.useNotification()
    const [KINSKD, setKINSKD] = useState()
    const [UserList, setUserList] = useState([])
    const [LionKingList, setLionKingList] = useState()

    const [DisCode, setDisCode] = useState()
    const [MicCode, setMicCode] = useState()
    const [AudioCode, setAudioCode] = useState()
    const [VideoCode, setVideoCode] = useState()

    const [DisData, setDisData] = useState()
    const [SelectData, setSelectData] = useState()

    const { runAsync } = useRequest(Http, { manual: true, onSuccess: res => setUserList(res.ipBroadcast) })

    const SDK_STATEEvent = useEventEmitter()
    SDK_STATEEvent.useSubscription(() => {
        api.success({ key: 'king', message: 'KING初始化成功', placement: 'topLeft' })
        deviceList(KINSKD, api, deviceListEvent)
    })

    const deviceListEvent = useEventEmitter()
    deviceListEvent.useSubscription(val => setLionKingList(val))

    const DEVICE_ALARM_STATEEvent = useEventEmitter()
    DEVICE_ALARM_STATEEvent.useSubscription(val => {
        const { type, TaskCode, Id } = val
        if (type === 'RING') {
            setDisCode(TaskCode)
            setDisData(UserList.find(v => Number(v.deviceSerial) === Id))
        } else {
            setDisCode()
            setDisData()
        }
    })

    useEffect(() => {
        if (KINSKD) {
            SDK_STATE(KINSKD, api, SDK_STATEEvent)
            DEVICE_STATE(KINSKD)
            DEVICE_ALARM_STATE(KINSKD, api, DEVICE_ALARM_STATEEvent)
        }
    }, [KINSKD, api, SDK_STATEEvent, DEVICE_ALARM_STATEEvent])

    useEffect(() => {
        const { Account, Password } = KING_ADMIN
        const sdk = new SOS.SDK({ Account, Password })
        InitLionKing(sdk, api)
        setKINSKD(sdk)
        return () => {
            DestructionKing(sdk)
        }
    }, [KING_ADMIN, api])

    useEffect(() => {
        runAsync({ url: 'getTalkIPBroadcast', data: { OrganizationUuid: org } })
    }, [org, runAsync])

    const TaskCodeEvent = useEventEmitter()
    TaskCodeEvent.useSubscription(val => {
        const { type, TaskCode } = val
        const codeMap = {
            kingMic: setMicCode,
            kingAudio: setAudioCode,
            kingVideo: setVideoCode,
        }
        codeMap[type](TaskCode)
    })

    const CloseEvent = useEventEmitter()
    CloseEvent.useSubscription(val => {
        const codeMap = {
            kingMic: setMicCode,
            kingAudio: setAudioCode,
            kingVideo: setVideoCode,
        }
        codeMap[val]()
    })

    const onMic = (data, e) => {
        setSelectData(e)
        microphoneMutilBoradcastStart(data)
    }

    const onAudio = (data, e) => {
        setSelectData(e)
        audioSpeakStart(data)
    }

    const onVideo = (data, e) => {
        setSelectData(e)
        videoMonitorStart(data)
    }

    const items = e => {
        const { broadcastType, deviceSerial } = e
        const data = { sdk: KINSKD, DeviceId: Number(deviceSerial), api, TaskCodeEvent }
        return [
            {
                key: '1',
                label: <div onClick={() => onMic(data, e)}>语音广播</div>,
                icon: <AudioOutlined />,
            },
            broadcastType > 1 && {
                key: '2',
                label: <div onClick={() => onAudio(data, e)}>语音对讲</div>,
                icon: <AudioOutlined />,
            },
            broadcastType > 2 && {
                key: '3',
                label: <div onClick={() => onVideo(data, e)}>视频对讲</div>,
                icon: <AudioOutlined />,
            },
        ]
    }

    return (
        <div className="PeripheralB01">
            {contextHolder}
            <div className="Alarm" style={{ right: DisCode ? 0 : -400 }}>
                <CommonSmallTitle title="告警呼叫">
                    <div className="Box">
                        <div>设备编号:{DisData?.deviceSerial}</div>
                        <div>设备名称:{DisData?.tableName}</div>
                        <div>
                            <Button type="primary" onClick={() => disconnectedCallback(KINSKD, DisCode, api)}>
                                接警
                            </Button>
                            <Button type="primary" onClick={() => deviceAlarmDone(KINSKD, DisCode, api)} danger>
                                结束
                            </Button>
                        </div>
                    </div>
                </CommonSmallTitle>
            </div>

            <div className="Mic" style={{ right: MicCode ? 0 : -400 }}>
                <CommonSmallTitle title="音柱广播">
                    <div className="Box">
                        <div>设备编号:{SelectData?.deviceSerial}</div>
                        <div>设备名称:{SelectData?.tableName}</div>
                        <Button
                            type="primary"
                            danger
                            onClick={() => microphoneMutilBoradcastStop(KINSKD, MicCode, api, CloseEvent)}
                        >
                            挂断
                        </Button>
                    </div>
                </CommonSmallTitle>
            </div>
            <div className="Audio" style={{ right: AudioCode ? 0 : -400 }}>
                <CommonSmallTitle title="音频对讲">
                    <div className="Box">
                        <audio id="html_audio_remote" autoPlay />
                        <div>设备编号:{SelectData?.deviceSerial}</div>
                        <div>设备名称:{SelectData?.tableName}</div>
                        <Button
                            type="primary"
                            danger
                            onClick={() => audioSpeakStop(KINSKD, AudioCode, api, CloseEvent)}
                        >
                            挂断
                        </Button>
                    </div>
                </CommonSmallTitle>
            </div>
            <div className="Video" style={{ right: VideoCode ? 0 : -600 }}>
                <CommonSmallTitle title="视频监控">
                    <div className="Box">
                        <video id="html_video_remote" autoPlay muted />
                        <div>
                            <Button
                                type="primary"
                                onClick={() =>
                                    audioSpeakStart({
                                        sdk: KINSKD,
                                        DeviceId: Number(SelectData?.deviceSerial),
                                        api,
                                        TaskCodeEvent,
                                    })
                                }
                            >
                                对讲
                            </Button>
                            <Button
                                type="primary"
                                danger
                                onClick={() => videoMonitorStop(KINSKD, VideoCode, api, CloseEvent)}
                            >
                                挂断
                            </Button>
                        </div>
                    </div>
                </CommonSmallTitle>
            </div>
            <Tree
                fieldNames={{ title: 'personName', key: 'uuid' }}
                treeData={UserList}
                titleRender={e => {
                    const { deviceSerial, tableName, parentUuid } = e
                    return (
                        <>
                            {parentUuid === '00000000-0000-0000-0000-000000000000' ? (
                                <div>{tableName}</div>
                            ) : (
                                <Dropdown menu={{ items: items(e) }} trigger={['click']}>
                                    <div className="personName">
                                        <div>
                                            {tableName} - {deviceSerial}
                                        </div>
                                        <div>
                                            {LionKingList
                                                ? LionKingList.includes(Number(deviceSerial))
                                                    ? '在线'
                                                    : '离线'
                                                : '初始化...'}
                                        </div>
                                    </div>
                                </Dropdown>
                            )}
                        </>
                    )
                }}
            />
        </div>
    )
}

const C01 = () => {
    return <div>C01</div>
}

const D01 = () => {
    return <div>D01</div>
}

export const Peripheral001 = ({
    title,
    type,
    CMT_ADMIN,
    ZL_ADMIN,
    MapSelect,
    sceneId,
    MapSetUp,
    MapOptions,
    KING_ADMIN,
    org,
}) => {
    const [Active, setActive] = useState([type[0]])
    const MenuList = { A01, B01, C01, D01 }

    return (
        <div className="Peripheral001">
            <div className="Box">
                <CommonSmallTitle title={title}>
                    <div className="body">
                        {type.map(item => (
                            <div className="header" key={item}>
                                <div
                                    className="title"
                                    onClick={() =>
                                        setActive(e =>
                                            e.includes(item) ? e.filter(str => str !== item) : [...e, item],
                                        )
                                    }
                                >
                                    <div>{menuTypeList[item]}</div>
                                    {Active.includes(item) ? <DownOutlined /> : <UpOutlined />}
                                </div>
                                <div className={`item ${Active.includes(item) ? 'Show' : 'Hidden'}`}>
                                    {(() => {
                                        const Template = MenuList[item]
                                        return (
                                            <Template
                                                ZL_ADMIN={ZL_ADMIN}
                                                CMT_ADMIN={CMT_ADMIN}
                                                KING_ADMIN={KING_ADMIN}
                                                sceneId={sceneId}
                                                org={org}
                                            />
                                        )
                                    })()}
                                </div>
                            </div>
                        ))}
                    </div>
                </CommonSmallTitle>
            </div>
            {(() => {
                const Template = MapList[MapSelect]
                return <Template sceneId={sceneId} MapSetUp={MapSetUp} MapOptions={MapOptions} type="Helmet" />
            })()}
        </div>
    )
}
